<template>
  <view class="quiz-container uni-pa-5">
    <!-- 头部信息 -->
    <view class="header ">
      <text class="title">
        <text class="bi bi-mortarboard"></text> 物理知识答题
      </text>
      <view class="uni-my-3">
        <text class="progress">{{ currentIndex + 1 }}/{{ questions.length }}</text>
      </view>
    </view>

    <!-- 题目导航 -->
    <scroll-view scroll-x class="question-nav uni-mx-2">
      <view class="nav-items">
        <view 
          v-for="(q, index) in questions" 
          :key="index"
          class="nav-item"
          :class="{
            'current': currentIndex === index,
            'answered': answeredQuestions[index],
            'correct': isQuestionCorrect(index),
            'wrong': isQuestionWrong(index)
          }"
          @tap="jumpToQuestion(index)"
        >
          {{ index + 1 }}
        </view>
      </view>
    </scroll-view>

    <!-- 题目内容 -->
    <view class="question-section">
      <view class="question uni-pa-4">
        <text class="question-index">Q{{ currentIndex + 1 }}.</text>
        {{ currentQuestion?.problem }}
      </view>
      <view class="options">
        <view 
          v-for="option in ['A', 'B', 'C', 'D']" 
          :key="option"
          class="option uni-my-3 uni-pa-5"
          :class="{
            'selected': userAnswers[currentIndex] === option,
            'correct': showResult && option === currentQuestion?.right,
            'wrong': showResult && userAnswers[currentIndex] === option && option !== currentQuestion?.right
          }"
          @tap="selectAnswer(option)"
        >
          <text class="option-label">{{ option }}</text>
          <text class="option-content">{{ currentQuestion?.[option] }}</text>
        </view>
      </view>

      <!-- 答案解析 -->
      <view v-if="showResult && currentQuestion" class="explanation">
        <text class="explanation-title">
          <text class="bi bi-info-circle"></text> 答案解析
        </text>
        <text class="explanation-content">{{ currentQuestion.description }}</text>
      </view>
    </view>

    <!-- 底部导航 -->
    <view class="navigation">
      <button 
        class="nav-btn"
        :class="{ 'disabled': currentIndex === 0 }"
        @tap="prevQuestion"
      >
        <text class="bi bi-arrow-left"></text> 上一题
      </button>
      
      <button 
        class="nav-btn primary"
        @tap="nextQuestion"
      >
        {{ currentIndex === questions.length - 1 ? '提交' : '下一题' }}
        <text class="bi bi-arrow-right" v-if="currentIndex !== questions.length - 1"></text>
      </button>
    </view>

    <!-- 得分弹窗 -->
    <uni-popup ref="scorePopup" type="center">
      <view class="score-popup">
        <view class="score-header">
          <text class="bi" :class="score >= 60 ? 'bi-emoji-smile' : 'bi-emoji-frown'"></text>
          <text class="score-title">答题完成！</text>
        </view>
        
        <view class="score-content">
          <text class="score-number">{{ score }}</text>
          <text class="score-label">分</text>
          <text class="score-detail">答对 {{ correctAnswers }} 题，获得 {{ score }} 积分</text>
          <text class="score-status">{{ score >= 60 ? '恭喜通过！' : '继续加油！' }}</text>
        </view>

        <view class="score-actions">
          <button class="action-btn" @tap="showAnalysis">
            <text class="bi bi-search"></text> 查看解析
          </button>
          <button class="action-btn primary" @tap="restartQuiz">
            <text class="bi bi-arrow-repeat"></text> 重新答题
          </button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useUserStore } from '@/stores/userStore';

const questions = ref([]);
const currentIndex = ref(0);
const userAnswers = ref({});
const showResult = ref(false);
const scorePopup = ref(null);
const score = ref(0);
const correctAnswers = ref(0);
const userStore = useUserStore();

// 当前题目
const currentQuestion = computed(() => questions.value[currentIndex.value]);

// 已答题的题目
const answeredQuestions = computed(() => {
  const answered = {};
  Object.keys(userAnswers.value).forEach(index => {
    answered[index] = true;
  });
  return answered;
});

// 判断题目是否回答正确
const isQuestionCorrect = (index) => {
  return showResult.value && userAnswers.value[index] === questions.value[index]?.right;
};

// 判断题目是否回答错误
const isQuestionWrong = (index) => {
  return showResult.value && userAnswers.value[index] && userAnswers.value[index] !== questions.value[index]?.right;
};

// 选择答案
const selectAnswer = (answer) => {
  if (showResult.value) return;
  userAnswers.value[currentIndex.value] = answer;
};

// 跳转到指定题目
const jumpToQuestion = (index) => {
  currentIndex.value = index;
};

// 上一题
const prevQuestion = () => {
  if (currentIndex.value > 0) {
    currentIndex.value--;
  }
};

// 下一题或提交
const nextQuestion = () => {
  if (currentIndex.value < questions.value.length - 1) {
    currentIndex.value++;
  } else {
    submitQuiz();
  }
};

// 计算得分
const calculateScore = () => {
  let correct = 0;
  questions.value.forEach((q, index) => {
    if (userAnswers.value[index] === q.right) {
      correct++;
    }
  });
  return {
    correctCount: correct,
    score: Math.round((correct / questions.value.length) * 100)
  };
};

// 提交答题
const submitQuiz = () => {
  const result = calculateScore();
  correctAnswers.value = result.correctCount;
  score.value = result.score;
  
  // 每道题答对奖励10积分
  const earnedPoints = result.correctCount * 10;
  userStore.updateUserInfo({
    ...userStore.userInfo,
    score: userStore.userInfo.score + earnedPoints
  });
  
  showResult.value = true;
  scorePopup.value?.open();
};

// 查看解析
const showAnalysis = () => {
  scorePopup.value?.close();
  currentIndex.value = 0;
};

// 重新答题
const restartQuiz = () => {
  userAnswers.value = {};
  currentIndex.value = 0;
  showResult.value = false;
  scorePopup.value?.close();
  fetchQuestions();
};

// 获取题库
const fetchQuestions = async () => {
  try {
    const response = await uni.request({
      url: 'https://fc-mp-d7d620be-76ea-43bb-a05a-d38ceb13c655.next.bspapp.com/problem',
      method: 'POST',
      data: {
        action: 'read'
      }
    });
    if (response.data.status === 1) {
      const allQuestions = response.data.data;
      questions.value = allQuestions
        .sort(() => Math.random() - 0.5)
        .slice(0, 20);
    }
  } catch (error) {
    uni.showToast({
      title: '获取题库失败',
      icon: 'error'
    });
  }
};

const handleAnswer = (isCorrect) => {
  if (isCorrect) {
    // 答对题目奖励10积分
    userStore.updateUserInfo({
      ...userStore.userInfo,
      score: userStore.userInfo.score + 10
    });
  }
  // ... 其他逻辑保持不变 ...
};

onMounted(() => {
  fetchQuestions();
});
</script>

<style lang="scss" scoped>
.quiz-container {
  min-height: 100vh;

 
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  
  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: var(--td-brand-color);
    
    .bi {
      margin-right: 10rpx;
    }
  }
  
  .progress {
    font-size: 28rpx;
    color: #666;
  }
}

.question-nav {
  background: #fff;

  height: 100%;
  border-bottom: 2rpx solid #f0f0f0;
  white-space: nowrap;
}

.nav-items {
  display: inline-flex;

  gap: 20rpx;
  justify-content: flex-start;
  align-items: center;
  min-width: 100%;
}

.nav-item {
  min-width: 70rpx;
  width: 70rpx;
  height: 70rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: #f5f5f5;
  color: #666;
  font-size: 28rpx;
  flex-shrink: 0;
  transition: all 0.3s ease;
  
  &.current {
    background: var(--td-brand-color);
    color: #fff;
    transform: scale(1.1);
  }
  
  &.answered {
    background: #e8e8e8;
    color: #999;
  }
  
  &.correct {
    background: #28a745;
    color: #fff;
  }
  
  &.wrong {
    background: #dc3545;
    color: #fff;
  }
  
  @media screen and (max-width: 375px) {
    min-width: 60rpx;
    width: 60rpx;
    height: 60rpx;
    font-size: 24rpx;
  }
}

.question-section {
  background: #fff;
  border-radius: 20rpx;

  
  .question {
    font-size: 32rpx;
    color: #333;
 
    display: block;
    
    .question-index {
      color: var(--td-brand-color);
      font-weight: bold;
      margin-right: 10rpx;
    }
  }
}

.options {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.option {
  display: flex;
  align-items: center;

  border-radius: 10rpx;
  background: #f8f8f8;
  transition: all 0.3s;
  
  &.selected {
    background: var(--td-brand-color);
    color: #fff;
  }
  
  &.correct {
    background: #28a745;
    color: #fff;
  }
  
  &.wrong {
    background: #dc3545;
    color: #fff;
  }
  
  .option-label {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.2);
    margin-right: 20rpx;
  }
}

.explanation {
  margin-top: 30rpx;
  padding-top: 30rpx;
  border-top: 2rpx solid #f0f0f0;
  
  .explanation-title {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 10rpx;
    display: block;
    
    .bi {
      color: var(--td-brand-color);
      margin-right: 10rpx;
    }
  }
  
  .explanation-content {
    font-size: 28rpx;
    color: #333;
    line-height: 1.6;
  }
}

.navigation {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  display: flex;
  justify-content: space-between;
  gap: 20rpx;
  background: #fff;
  box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.nav-btn {
  flex: 1;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 40rpx;
  font-size: 28rpx;
  
  &.primary {
    background: var(--td-brand-color);
    color: #fff;
  }
  
  &.disabled {
    opacity: 0.5;
    pointer-events: none;
  }
  
  .bi {
    margin: 0 10rpx;
  }
}

.score-popup {
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  width: 600rpx;
  text-align: center;
  
  .score-header {
    margin-bottom: 30rpx;
    
    .bi {
      font-size: 80rpx;
      color: var(--td-brand-color);
      margin-bottom: 20rpx;
      display: block;
    }
    
    .score-title {
      font-size: 36rpx;
      font-weight: bold;
    }
  }
  
  .score-content {
    margin-bottom: 40rpx;
    
    .score-number {
      font-size: 80rpx;
      font-weight: bold;
      color: var(--td-brand-color);
    }
    
    .score-label {
      font-size: 32rpx;
      color: #666;
      margin-left: 10rpx;
    }
    
    .score-detail {
      font-size: 28rpx;
      color: #666;
      margin-top: 20rpx;
      display: block;
    }
    
    .score-status {
      font-size: 32rpx;
      color: var(--td-brand-color);
      margin-top: 10rpx;
      display: block;
    }
  }
  
  .score-actions {
    display: flex;
    gap: 20rpx;
    
    .action-btn {
      flex: 1;
      height: 80rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 40rpx;
      font-size: 28rpx;
      
      &.primary {
        background: var(--td-brand-color);
        color: #fff;
      }
      
      .bi {
        margin-right: 10rpx;
      }
    }
  }
}

.question-nav::-webkit-scrollbar {
  display: none;
}
</style> 